using UnityEngine;

public class TGS_EnemyTankManager_Script : MonoBehaviour
{
    [Header("敌方坦克预设体")]
    public GameObject enemyTankPrefab;
    [Header("生成时间间隔")] 
    public float interval = 1f;
    [Header("敌方坦克的最多数量")]
    [Range(40, 100)]
    public int maxEnemy = 50;

    // 计时器
    private float timer;
    // 计数器
    private int counter;

    private void Update()
    {
        timer += Time.deltaTime;
        if (timer>interval)
        {
            // 生成敌方坦克
            if (counter < maxEnemy)
            {
                CreateTank();
                counter++;
            }
            // 计时器归0
            timer = 0;
        }
    }

    private void CreateTank()
    {
        // 位置范围([-50, 0, -50], [50, 0, 50])
        float x, z;
        Vector3 position;
        do
        { 
            x = Random.Range(-50f, 50f); 
            z = Random.Range(-50f, 50f);
            position = new Vector3(x, 0, z);
        } while (invalidPosition(position));
        // 随机旋转
        float angle = Random.Range(0f, 360f);
        // 将欧拉角转换为四元数
        Quaternion rotation = Quaternion.Euler(0f, angle, 0f);
        // 生成坦克
        Instantiate(enemyTankPrefab, position, rotation);
    }

    private bool invalidPosition(Vector3 position)
    {
        // 检测半径为2的球体内是否有物体, 排除layer层为8的物体: 拓展-排除8和9两层：~(1<<8|1<<9)
        return Physics.CheckSphere(position, 2, ~(1 << 8));
    }
}